package com.eh.proxy.remote.remote;

import com.eh.proxy.remote.remote.model.GumballMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Random;

/**
 * Created by David on 2016/5/2.
 */
public class GumballMachineRemoteTest {
    private static Logger logger = LoggerFactory.getLogger(GumballMachineRemoteTest.class);

    public static void main(String[] args) {
        try {
            GumballMachine gumballMachine = new GumballMachine(20, "北京");
            LocateRegistry.createRegistry(6600);
            Naming.rebind("rmi://127.0.0.1:6600/bj_gumballMachine", gumballMachine);
            logger.info("开启服务");
            mockChange(gumballMachine);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private static void mockChange(GumballMachine gumballMachine) {
        while (true) {
            if (gumballMachine.getCount() >= 0) {
                testSell(gumballMachine);
            }
        }
    }

    private static void testSell(GumballMachine gumballMachine) {
        gumballMachine.insertQuarter();
        mockPause();
        gumballMachine.turnCrank();
        mockPause();
    }

    private static void mockPause() {
        try {
            Random r = new Random(System.currentTimeMillis());
            Thread.sleep(r.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
